﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace trunk.Views
{
    /// <summary>
    /// TcpListener.xaml 的交互逻辑
    /// </summary>
    public partial class TcpListenerWindow : Window
    {
        private TcpListener _tcpListener;
        private Task _listeningTask;
        private bool _isListening;
        private List<TcpClient> _clients = new List<TcpClient>();

        public TcpListenerWindow()
        {
            InitializeComponent();
        }

        private async void StartListeningButton_Click(object sender, RoutedEventArgs e)
        {
            if (!_isListening)
            {
                try
                {
                    _tcpListener = new TcpListener(IPAddress.Any, 8888);
                    _tcpListener.Start();

                    _isListening = true;
                    _listeningTask = Task.Run(ListenForClients);

                    MessageBox.Show("开始监听连接。");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"启动监听时出错: {ex.Message}");
                }
            }
        }

        private async Task ListenForClients()
        {
            while (_isListening)
            {
                try
                {
                    TcpClient client = await _tcpListener.AcceptTcpClientAsync();
                    _clients.Add(client);

                    Dispatcher.Invoke(() =>
                    {
                        ClientListBox.Items.Add(new { ClientInfo = $"客户端 {_clients.Count}", Client = client });
                    });
                }
                catch (SocketException)
                {
                    break;
                }
            }
        }

        private async void StopListeningButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isListening)
            {
                try
                {
                    _isListening = false;
                    _tcpListener.Stop();

                    if (_listeningTask != null)
                    {
                        await _listeningTask;
                    }

                    foreach (var client in _clients)
                    {
                        client.Close();
                    }
                    _clients.Clear();
                    ClientListBox.Items.Clear();

                    MessageBox.Show("停止监听连接。");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"停止监听时出错: {ex.Message}");
                }
            }
        }

        private void SendMessageButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button sendButton)
            {
                if (sendButton.Parent is StackPanel stackPanel)
                {
                    if (stackPanel.Children[1] is TextBox messageTextBox)
                    {
                        string message = messageTextBox.Text;

                        //if (ClientListBox.ItemContainerGenerator.ContainerFromItem(ClientListBox.SelectedItem) is ListBoxItem listBoxItem)
                        //{
                        //    var item = (dynamic)ClientListBox.ItemContainerGenerator.ItemFromContainer(listBoxItem);
                        //    TcpClient client = item.Client;

                        //    try
                        //    {
                        //        NetworkStream stream = client.GetStream();
                        //        byte[] data = Encoding.UTF8.GetBytes(message);
                        //        stream.Write(data, 0, data.Length);
                        //    }
                        //    catch (Exception ex)
                        //    {
                        //        MessageBox.Show($"发送消息时出错: {ex.Message}");
                        //    }
                        //}
                        //(dynamic)ClientListBox.ItemContainerGenerator.ItemFromContainer(listBoxItem);
                        dynamic item = sendButton.DataContext;
                        TcpClient client = item.Client;

                        try
                        {
                            NetworkStream stream = client.GetStream();
                            byte[] data = Encoding.UTF8.GetBytes(message);
                            stream.Write(data, 0, data.Length);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"发送消息时出错: {ex.Message}");
                        }
                    }
                }
            }
        }
    }
}
